wpWidgets = (function(){
	var reminded = false;
	var lameWidgetReminder = function() {
		if ( reminded )
			return;
		window.onbeforeunload = function () { return widgetsL10n.lamerReminder };
		jQuery('div.wrap:first').prepend( '<div class="updated" style="display:none"><p>' + widgetsL10n.lameReminder + '</p></div>' ).children( ':first' ).slideDown();
		jQuery('#current-widgets .submit input[name=save-widgets]').css( 'background-color', '#ffffe0' ).click( function() {
			window.onbeforeunload = null;
		} );
		reminded = true;
	};

	var increment = 1;

	// Open or close widget control form
	var toggleWidget = function( li, disableFields ) {
		var width = li.find('input.widget-width').val();

		// it seems IE chokes on these animations because of the positioning/floating
		var widgetAnim = jQuery.browser.msie ? function() {
			var t = jQuery(this);
			if ( t.is(':visible') ) {
				if ( disableFields ) { t.find( ':input:enabled' ).not( '[name="widget-id[]"], [name*="[submit]"]' ).attr( 'disabled', 'disabled' ); }
				li.css( 'marginLeft', 0 );
				t.siblings('div').children('h4').children('a').text( widgetsL10n.edit );
			} else {
				t.find( ':disabled' ).attr( 'disabled', '' ); // always enable on open
				if ( width > 250 )
					li.css( 'marginLeft', ( width - 250 ) * -1 );
				t.siblings('div').children('h4').children('a').text( widgetsL10n.cancel );
			}
			t.toggle();
		} : function() {
			var t = jQuery(this);

			if ( t.is(':visible') ) {
				if ( disableFields ) { t.find( ':input:enabled' ).not( '[name="widget-id[]"], [name*="[submit]"]' ).attr( 'disabled', 'disabled' ); }
				if ( width > 250 )
					li.animate( { marginLeft: 0 } );
				t.siblings('div').children('h4').children('a').text( widgetsL10n.edit );
			} else {
				t.find( ':disabled' ).attr( 'disabled', '' ); // always enable on open
				if ( width > 250 )
					li.animate( { marginLeft: ( width - 250 ) * -1 } );
				t.siblings('div').children('h4').children('a').text( widgetsL10n.cancel );
			}
			t.animate( { height: 'toggle' } );
		};

		return li.children('div.widget-control').each( widgetAnim ).end();
	};

	// onclick for edit/cancel links
	var editClick = function() {
		var q = wpAjax.unserialize( this.href );
		// if link is in available widgets list, make sure it points to the current sidebar

		if ( ( q.sidebar && q.sidebar == jQuery('#sidebar').val() ) || q.add ) {
			var w = q.edit || q.add;
			toggleWidget( jQuery('#current-sidebar .widget-control-list input[@name^="widget-id"][@value=' + w + ']').parents('li:first'), false ).blur();
			return false;
		} else if ( q.sidebar ) { // otherwise, redirect to correct page
			return true;
		}
		// If link is in current widgets list, just open the form
		toggleWidget( jQuery(this).parents('li:first'), true ).blur();
		
		return false;
	};

	// onclick for add links
	var addClick = function() {
		var oldLi = jQuery(this).parents('li:first').find('ul.widget-control-info li');
		var newLi = oldLi.clone();
		
		if ( newLi.html().match( /%i%/ ) ) {
			// supplid form is a template, replace %i% by unique id
			var i = jQuery('#generated-time').val() + increment.toString();
			increment++;
			newLi.html( newLi.html().replace( /%i%/g, i ) );
		} else {
			jQuery(this).text( widgetsL10n.edit ).unbind().click( editClick );
			// save form content in textarea so we don't have any conflicting HTML ids
			oldLi.html( '<textarea>' + oldLi.html() + '</textarea>' );
		}

		// add event handlers
		addWidgetControls( newLi );

		// add widget to sidebar sortable
		widgetSortable.append( newLi ).SortableAddItem( newLi[0] );

		// increment widget counter
		var n = parseInt( jQuery('#widget-count').text(), 10 ) + 1;
		jQuery('#widget-count').text( n.toString() )

		lameWidgetReminder();
		return false;
	};

	// add event handlers to all links found in context
	var addWidgetControls = function( context ) {

		if ( !context )
			context = document;

		jQuery('a.widget-control-edit', context).click( editClick );

		// onclick for save links
		jQuery('a.widget-control-save', context).click( function() {
			lameWidgetReminder();
			toggleWidget( jQuery(this).parents('li:first'), false ).blur()
			return false;
		} );

		// onclick for remove links
		jQuery('a.widget-control-remove', context).click( function() {
			var w = jQuery(this).parents('li:first').find('input[@name^="widget-id"]').val();
			jQuery(this).parents('li:first').remove();
			var t = jQuery('#widget-list ul#widget-control-info-' + w + ' textarea');
			t.parent().html( t.text() ).parents('li.widget-list-item:first').children( 'h4' ).children('a.widget-action')
				.show().text( widgetsL10n.add ).unbind().click( addClick );
			var n = parseInt( jQuery('#widget-count').text(), 10 ) - 1;
			jQuery('#widget-count').text( n.toString() )
			return false;
		} );
	}

	var widgetSortable;
	var widgetSortableInit = function() {
		try { // a hack to make sortables work in jQuery 1.2+ and IE7
			jQuery('#current-sidebar .widget-control-list').SortableDestroy();
		} catch(e) {}
		widgetSortable = jQuery('#current-sidebar .widget-control-list').Sortable( {
			accept: 'widget-sortable',
			helperclass: 'sorthelper',
			handle: 'h4.widget-title',
			onStop: widgetSortableInit
		} );
	}
	
	return{

		init: function(){
			jQuery('.noscript-action').remove();
			
			addWidgetControls();
			jQuery('a.widget-control-add').click( addClick );
			widgetSortableInit();
		},
		
		refresh: function(){
			addWidgetControls();
			widgetSortableInit();
		}
				
	}
})();


widgetsAdmin = (function(){
	var updateDOM = function (inputField){
	    // if the inputField ID string has been passed in, get the inputField object
	    if (typeof inputField == "string") {
	        inputField = document.getElementById(inputField);
	    }
	
	    if (inputField.type == "select-one") {
	        for (var i=0; i<inputField.options.length; i++) {
	            if (i == inputField.selectedIndex) {
	                inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
	            }
	        }
	    } else if (inputField.type == "text") {
	        inputField.setAttribute("value",inputField.value);
	    } else if (inputField.type == "textarea") {
	    	inputField.innerHTML=inputField.value;
	        inputField.setAttribute("value",inputField.value);
	    } else if ((inputField.type == "checkbox") || (inputField.type == "radio")) {
	        if (inputField.checked) {
	            inputField.setAttribute("checked","checked");
	        } else {
	            inputField.removeAttribute("checked");
	        }
	    }
	}
	
	return{
		init: function(){
			if(jQuery('#copy_sidebar_trigger').length == 0) return; // temp fix
			nonce = jQuery('#op_clipboard_nonce').val();
			jQuery.ajax({
				type: 'post',
				url: 'admin-ajax.php',
				data: 'action=op_widgetsadmin&method=inclipboard&nonce='+nonce,
				success: widgetsAdmin.handlePaste
			});
			
			jQuery('#copy_sidebar_trigger').click(widgetsAdmin.copy);
			jQuery('#paste_sidebar_trigger').click(widgetsAdmin.paste);
		},
		
		handlePaste: function(e){
			if(e == 'TRUE')
				jQuery('#paste_sidebar_trigger').get(0).disabled = false;
		},
		
		copy: function(){
			jQuery('#current-sidebar').find(':input').each(function(){
				updateDOM(this);
			});
			
			var contents = jQuery('#current-sidebar').html();
			contents = encodeURIComponent(contents);
			nonce = jQuery('#op_clipboard_nonce').val();
			jQuery.ajax({
				type: 'post',
				url: 'admin-ajax.php',
				data: 'action=op_widgetsadmin&method=copy&nonce='+nonce+'&html='+contents
			});
			jQuery('#paste_sidebar_trigger').get(0).disabled = false;
			return false;
		},
		
		paste: function(){
			if(confirm('Paste sidebar from clipboard?  Warning: Widgets currently in this sidebar will be lost')){
				nonce = jQuery('#op_clipboard_nonce').val();
				jQuery.ajax({
					type: 'post',
					url: 'admin-ajax.php',
					data: 'action=op_widgetsadmin&method=paste&nonce='+nonce+'&sidebar='+jQuery('#sidebar').val(),
					success: widgetsAdmin.doPaste
				});
			}

			return false;			
		},
		
		doPaste: function(e){
			if(e.length == 0) return;
			jQuery('#current-sidebar').html(e.replace(/\\/g,''));
			wpWidgets.refresh();
		}
	}
})();

jQuery(document).ready(widgetsAdmin.init);
jQuery(document).ready(wpWidgets.init);